package test.juc;

import test.bean.User;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by shuoGG on 2018/10/25
 */
public class AsyncToSync {
    private Map<Integer, User> uMap = new ConcurrentHashMap<>();

    private AtomicInteger sid = new AtomicInteger(0);

    public void sendRequestSingle(int sessionId) throws InterruptedException {
        createSessionSingle(sessionId);
        System.out.println(Thread.currentThread().getName() + " sendRequest Enter...sessionId:" + sessionId);
        synchronized (uMap.get(sessionId)) {
            uMap.get(sessionId).wait();
        }
        System.out.println(Thread.currentThread().getName() + " sendRequest awake...sessionId:" + sessionId);
    }

    public void recAckMulti(int sessionId) {
        User user = uMap.get(sessionId);
        user.setAge(user.getAge() + 1);
        if (user.getAge() == user.getSex()) {
            synchronized (uMap.get(sessionId)) {
                uMap.get(sessionId).notify();
            }
        }
    }

    public void recAckSingle(int sessionId) {
        System.out.println(Thread.currentThread().getName() + " recAckSingle");
        synchronized (uMap.get(sessionId)) {
            uMap.get(sessionId).notify();
        }
    }

    private void createSessionSingle(int sid) {
        System.out.println(Thread.currentThread().getName() + " createSessionSingle");
        User user = new User("Tom", 0, 5);
        uMap.put(sid, user);
    }

    public void sleep(int sec) {
        try {
            Thread.sleep(sec * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
